<?php

namespace common\domain\components\filters;

use common\domain\helper\Log;
use common\domain\helper\Request;
use yii\base\ActionFilter;

class RequestId extends ActionFilter
{
    protected static $timeStart;

    /**
     * @param \yii\base\Action $action
     *
     * @return bool
     * @throws \yii\web\BadRequestHttpException
     */
    public function beforeAction($action): bool
    {
        self::$timeStart = microtime(true);

        // 生成ReqID
        $prefix = session_create_id(date('YmdHis'));
        $request_id = strtoupper(md5(uniqid($prefix, true)));

        \Yii::$app->params['reqId'] = $request_id;

        return parent::beforeAction($action);
    }

    /**
     * @param \yii\base\Action $action
     * @param mixed $result
     *
     * @return mixed
     */
    public function afterAction($action, $result)
    {
        $cost = round(microtime(true) - self::$timeStart, 6);
        $act = '/' . \Yii::$app->controller->id . '/' . $action->id;
        $req = Request::getRequest() ? json_encode(Request::getRequest()) : '';
        $res = \is_array($result) ? json_encode($result) : $result;

        // Log写入请求信息  执行时间 路径 请求参数 返回值
        Log::printLog("[{$act}][{$cost}][{$req}][{$res}]", 'exe');

        // 给前端返回ReqID
        $result['req_id'] = \Yii::$app->params['reqId'];

        return parent::afterAction($action, $result);
    }
}
